import {
  C13BottomDock,
  CategoryTag,
  Header,
  Icon,
  Layout,
  PriceView,
  UserSubPageBase,
  KeyValueList,
  AbstractImage,
} from "@/components";
import { ApiItemTypeMapping } from "@/data/shared/entityShapes";
import { ModalTypes, useApplicationInfo } from "@/store/applicationDataContext";
import {
  getOrderDetail,
  getPaymentInfo,
  cancelOrder,
  confirmOrder,
  refundProduct,
  getOrderPaymentStatus,
  requestSubscribeMessage,
} from "@/store/userDataContext";
import { apiItemTypeMapping, apiItemTypeMappingC } from "@/utils/apiMapping";
import { ApiTalkTypes } from "@/data/talks/talkTypes";
import { getTimeRemaining } from "@/utils/dateTimeFormatHelpers";
import { navigateTo, switchTab } from "@/utils/navigation";
import { View, Text } from "@tarojs/components";
import Taro, {
  getCurrentPages,
  redirectTo,
  useDidHide,
  useDidShow,
  useRouter,
} from "@tarojs/taro";
import { useAuth } from "@/store/authContext";
import { useCallback, useEffect, useState } from "react";
import notifications from "@/data/notifications";
import { REVIEW_SUBMITTED_KEY } from "@/components/layout/WithModal";
import { BottomDockButtonShape } from "@/components/c13-BottomDock";
import {
  ApiOrderStatus,
  ApiRefundStatus,
  OrderDetailShape,
} from "@/data/order/orderTypes";
import style from "./index.module.scss";
import { setTimeout } from "timers";

const UI_TEXT: {
  [key in ApiItemTypeMapping]: {
    topText: string;
    priceText: {
      main?: string;
      supplementary?: string;
      totalIntro: string;
      summaryFormatter: (peopleCount: number, productCount: number) => string;
    };
  };
} = {
  [ApiItemTypeMapping.Course]: {
    topText: "课程预约信息",
    priceText: {
      main: "课程费用",
      supplementary: "礼品卡",
      totalIntro: "",
      summaryFormatter: (peopleCount) => `共${peopleCount}人`,
    },
  },
  [ApiItemTypeMapping.CourseDiscovery]: {
    topText: "课程预约信息",
    priceText: {
      main: "课程费用",
      supplementary: "礼品卡",
      totalIntro: "",
      summaryFormatter: (peopleCount) => `共${peopleCount}人`,
    },
  },
  [ApiItemTypeMapping.Talk]: {
    topText: "讲座预约信息",
    priceText: {
      main: "讲座费用",
      supplementary: "礼品卡",
      totalIntro: "",
      summaryFormatter: (peopleCount) => `共${peopleCount}人`,
    },
  },

  [ApiItemTypeMapping.Exhibition]: {
    topText: "展览预约信息",
    priceText: {
      main: "展览费用",
      supplementary: "相关出版物",
      totalIntro: "",
      summaryFormatter: (peopleCount, productCount) =>
        `共${peopleCount}人，${productCount}件商品`,
    },
  },
  [ApiItemTypeMapping.ShopItem]: {
    topText: "",
    priceText: {
      totalIntro: "",
      summaryFormatter: (_, productCount) => `共${productCount}件商品`,
    },
  },
};

// Notes:
// - Block - level elements not dealing with vertical spacing, as better done with incoming data
// - Only for elements that exist in event-order details (shopitems marked orange in Figma)
export default function UserOrderDetails() {
  const { dispatchAuthAction } = useAuth();
  const { params } = useRouter();
  const orderNo = params.orderNo!;
  const [orderDetail, setOrderDetail] = useState<OrderDetailShape | null>(null);
  const [orderStatus, setOrderStatus] = useState("");
  const { dispatch, applicationState } = useApplicationInfo();
  const [cdTime, setCdTime] = useState("");
  let countDownInterval: any = 0;

  const fetchOrderData = () => {
    if (orderNo) {
      const fetchData = async () => {
        const detail = await getOrderDetail({
          query: { orderNo: orderNo },
          authDispatch: dispatchAuthAction,
        });
        if (detail) {
          setOrderDetail(detail);
          setOrderStatus(detail.orderStatus);
        }
      };
      fetchData();
    }
  };

  // Refetch if updates to review-state
  useEffect(() => {
    if (applicationState.reviewOrderNumber == REVIEW_SUBMITTED_KEY) {
      fetchOrderData();
      applicationState.reviewOrderNumber = null;
    }
  }, [applicationState.reviewOrderNumber]);

  useDidShow(() => {
    fetchOrderData();
  });

  useDidHide(() => {
    countDownInterval && clearInterval(countDownInterval);
  });

  const initializeClock = useCallback(
    (dl) => {
      return setInterval(() => {
        const t = getTimeRemaining(dl);
        setCdTime(t.hours + ":" + t.minutes + ":" + t.seconds);
        if (t.total <= 0) {
          countDownInterval && clearInterval(countDownInterval);
          setCdTime("");
          setOrderStatus("已取消");
          setPrimaryCta(GO_HOME);
          setSecondaryCta({
            cb: goDetailPage,
            text: `查看该${apiItemTypeMappingC[orderDetail!.type]}`,
          });
        }
      }, 1000);
    },
    [orderDetail]
  );

  const rePay = async () => {
    const handleComplete = async (orderNumber: string) => {
      await getOrderPaymentStatus({
        query: { orderNo: [orderNumber] },
        authDispatch: dispatchAuthAction,
      });

      if (orderDetail!.type !== ApiItemTypeMapping.ShopItem) {
        requestSubscribeMessage([
          notifications.order.created,
          notifications.event.book,
          notifications.event.unbook,
        ]);
      } else {
        requestSubscribeMessage([
          notifications.order.created,
          notifications.order.canceled,
        ]);
      }
      setTimeout(() => {
        redirectTo({
          url: `/pages/user-order-details/index?orderNo=${orderNo}`,
        });
      }, 1000);
    };
    if (orderNo) {
      const { jsConfig, paymentRequire } = await getPaymentInfo({
        query: { orderNo: [orderNo] },
      });
      if (paymentRequire) {
        Taro.requestPayment({
          timeStamp: jsConfig.timeStamp,
          nonceStr: jsConfig.nonceStr,
          package: jsConfig.packages,
          signType: jsConfig.signType,
          paySign: jsConfig.paySign,
          complete() {
            handleComplete(orderNo);
          },
        });
      } else {
        redirectTo({ url: `/pages/order-status/index` });
      }
    }
  };

  const cancel = async () => {
    if (orderNo) {
      const msg = await cancelOrder({
        query: { orderNo: [orderNo] },
        authDispatch: dispatchAuthAction,
      });
      if (msg === "操作成功") {
        setCdTime("");
        countDownInterval && clearInterval(countDownInterval);
        setOrderStatus("已取消");
        setPrimaryCta(GO_HOME);
        setSecondaryCta({
          cb: goDetailPage,
          text: `查看该${apiItemTypeMappingC[orderDetail!.type]}`,
        });
      }
    }
  };

  const refund = () => {
    if (orderNo) {
      navigateTo(`pages/user-refund/index?orderNo=${orderNo}`);
    }
  };

  const refundBeforeSend = async () => {
    if (orderNo) {
      const refundStatus = await refundProduct({
        query: { orderNo: orderNo },
        authDispatch: dispatchAuthAction,
      });
      if (refundStatus) {
        navigateTo(`pages/user-refund-detail/index?orderNo=${orderNo}`);
      }
    }
  };

  const redeem = () => {
    dispatch({ type: "SHOW_MODAL", data: ModalTypes.QR });
  };

  const afterSales = () => {
    navigateTo(`pages/user-refund-detail/index?orderNo=${orderNo}`);
  };

  const gotoMe = () => {
    switchTab("pages/user/index");
  };

  const gotoGift = () => {
    navigateTo("pages/user-gift-certificates/index");
  };

  const goBackHome = () => {
    if (orderDetail!.type === ApiItemTypeMapping.ShopItem) {
      switchTab("pages/shop/index");
    } else {
      switchTab("pages/discover/index");
    }
  };

  const confirm = async () => {
    const confirmed = await confirmOrder({
      query: { orderNo: orderNo },
      authDispatch: dispatchAuthAction,
    });
    if (confirmed) {
      setOrderStatus("已收货"); // todo Luke
      setPrimaryCta(GO_HOME);
      setSecondaryCta(REFUND);
    }
  };

  const goDetailPage = () => {
    const id = orderDetail!.mainId
      ? orderDetail!.mainId
      : orderDetail!.productId
        ? orderDetail!.productId
        : "";
    if (orderDetail) {
      navigateTo(
        //@ts-ignore
        `pages/${apiItemTypeMapping[orderDetail.type]}-detail/index?id=${id}`
      );
    }
  };

  const DEFAULT_PRIMARY_CTA_REBOOK = {
    //0
    cb: rePay,
    text: "立即支付",
  };
  const DEFAULT_SECONDARY_CTA_NULL = null;

  const GO_HOME = {
    cb: goBackHome,
    text: "探索更多",
  };

  const REFUND = {
    cb: refund,
    text: "申请退款",
  };

  const AFTER_SALES = {
    cb: afterSales,
    text: "售后详情",
  };

  const REFUND_PRODUCT = {
    cb: refundBeforeSend,
    text: "退款",
  };

  const [primaryCta, setPrimaryCta] = useState<BottomDockButtonShape>(
    DEFAULT_PRIMARY_CTA_REBOOK
  );
  const [secondaryCta, setSecondaryCta] =
    useState<BottomDockButtonShape | null>(DEFAULT_SECONDARY_CTA_NULL);

  useEffect(() => {
    if (orderDetail) {
      setPrimaryCta(DEFAULT_PRIMARY_CTA_REBOOK);
      setSecondaryCta(DEFAULT_SECONDARY_CTA_NULL);

      if (!orderDetail.paid && !orderDetail.isDel) {
        setSecondaryCta({
          cb: cancel,
          text: "取消订单",
        });
        if (
          orderDetail.unpaidCountdown &&
          //@ts-ignore
          new Date() - new Date(orderDetail.unpaidCountdown) < 0
        ) {
          countDownInterval = initializeClock(
            new Date(orderDetail.unpaidCountdown)
          );
        }
      } else {
        if (orderDetail.paid) {
          if (orderDetail.type === ApiItemTypeMapping.ShopItem) {
            if (orderDetail.refundStatus === ApiRefundStatus.NotRefunded) {
              switch (orderDetail.status) {
                case ApiOrderStatus.NotShipped:
                  setPrimaryCta(REFUND_PRODUCT);
                  break;
                case ApiOrderStatus.ToBeRecieved:
                  setPrimaryCta({
                    cb: confirm,
                    text: "确认收货",
                  });
                  setSecondaryCta(GO_HOME);
                  break;
                // case ApiOrderStatus.CompletedNotYetEval:
                //   // TODO: TALK LUKE: NOT POSSIBLE TO END UP HERE?
                //   break;
                case ApiOrderStatus.CompletedAndEvaluated:
                  setPrimaryCta(GO_HOME);
                  if (
                    !orderDetail.isAfterSalesTime ||
                    (orderDetail.isAfterSalesTime && orderDetail.isGiftCard)
                  ) {
                    setSecondaryCta(REFUND);
                  }
                  break;

                default:
                  break;
              }
            } else {
              //退款中 //已取消（全部） //已收货
              setPrimaryCta(GO_HOME);
              setSecondaryCta(AFTER_SALES);
            }
          } else {
            if (orderDetail.status === 2) {
              //已完成待评价
              setPrimaryCta({
                //6
                cb: () => {
                  if (orderDetail) {
                    dispatch({
                      type: "SHOW_REVIEW_MODAL",
                      data: orderDetail.orderNo,
                    });
                  }
                },
                text: "评价",
              });
            } else {
              //其他
              setPrimaryCta(GO_HOME);
            }
            setSecondaryCta({
              cb: goDetailPage,
              text: `查看该${apiItemTypeMappingC[orderDetail.type]}`,
            });
          }
        }
        if (orderDetail.isDel) {
          setPrimaryCta(GO_HOME);
          if (orderDetail.type === ApiItemTypeMapping.ShopItem) {
            if (orderDetail.refundStatus !== ApiRefundStatus.NotRefunded) {
              setSecondaryCta(AFTER_SALES);
            }
          } else {
            setSecondaryCta({
              cb: goDetailPage,
              text: `查看该${apiItemTypeMappingC[orderDetail.type]}`,
            });
          }
        }
      }
    }
    return () => {
      countDownInterval && clearInterval(countDownInterval);
    };
  }, [orderDetail]);

  return (
    <Layout>
      {orderDetail && (
        <>
          <UserSubPageBase title={orderStatus} scrollable>
            {cdTime && <View>请在 {cdTime} 内完成支付</View>}
            {orderDetail.courseInfoDetails && (
              <>
                {orderDetail.paid &&
                  !orderDetail.isDel &&
                  orderDetail.talkType !== 2 && (
                    <View className={style["qr-button"]} onClick={redeem}>
                      <Icon className={style["qr-icon"]} type="QR" />
                      <View className={`title-s`}>点击会员码，扫码入场</View>
                    </View>
                  )}
                <View
                  className={`${style["event-info"]} ${style["top-border-section"]}`}
                >
                  <CategoryTag
                    categoryName={orderDetail.courseInfoDetails.typeName}
                    themeColor={orderDetail.courseInfoDetails.typeLabelColor}
                  />

                  <Header type="heading-n">
                    {orderDetail.courseInfoDetails.name}
                  </Header>
                  {orderDetail.courseInfoDetails.schedulings &&
                    orderDetail.courseInfoDetails.schedulings.length &&
                    orderDetail.courseInfoDetails.schedulings.map(
                      (scheduling) => (
                        <KeyValueList
                          itemList={[
                            {
                              leftText: "预约时间",
                              middleTextTop: scheduling.schedulingDate,
                              middleTextBottom: `${scheduling.schedulingStartTime} - ${scheduling.schedulingEndTime}`,
                            },
                            {
                              leftText: `${apiItemTypeMappingC[orderDetail.type]
                                }语言`,
                              middleTextTop: scheduling.language,
                            },
                            {
                              leftText:
                                orderDetail.courseInfoDetails.talkType ===
                                  ApiTalkTypes.Online
                                  ? "直播平台"
                                  : `${apiItemTypeMappingC[orderDetail.type]
                                  }地点`,
                              middleTextTop:
                                orderDetail.courseInfoDetails.talkType ===
                                  ApiTalkTypes.Online
                                  ? "微信直播"
                                  : scheduling.courseAddress.courseAddress,
                              middleTextBottom:
                                orderDetail.courseInfoDetails.talkType ===
                                  ApiTalkTypes.Online
                                  ? ""
                                  : scheduling.courseAddress.courseAddressInfo,
                            },
                          ]}
                        />
                      )
                    )}
                  <KeyValueList
                    itemList={[
                      {
                        leftText: "预约人员",
                        middleTextTop: orderDetail.lecturerName,
                      },
                      {
                        leftText: "预约手机号",
                        middleTextTop: orderDetail.lecturerPhone,
                      },
                      // {
                      //   leftText: "推荐人会员号",
                      //   middleTextTop: '293',
                      // },
                    ]}
                  />

                  <KeyValueList
                    itemList={[
                      {
                        leftText: `${apiItemTypeMappingC[orderDetail.type]
                          }费用`,
                        rightNode: (
                          <PriceView
                            className={style.price}
                            price={orderDetail.proTotalPrice}
                            type={"heading-n"}
                          />
                        ),
                      },

                      ...(orderDetail.couponPrice
                        ? [
                          {
                            leftText:
                              UI_TEXT[orderDetail.type].priceText
                                .supplementary!,
                            rightNode: (
                              <PriceView
                                className={style.price}
                                price={-orderDetail.couponPrice}
                                type={"heading-n"}
                              />
                            ),
                          },
                        ]
                        : []),
                    ]}
                  />
                </View>
              </>
            )}

            {orderDetail.preOrderProductDetails &&
              orderDetail.preOrderProductDetails.length > 0 && (
                <View>
                  {orderDetail.isGiftCard ? (
                    <View
                      className={`${style["top-border-section"]} ${style["bottom-border-section"]} ${style["misc-info"]}`}
                    >
                      <View className={style["misc-title"]}>
                        <Header type="heading-s">礼品卡</Header>
                      </View>
                      <View className={style["misc-content"]}>
                        请在
                        <Text className={style["clickables"]} onClick={gotoMe}>
                          我的
                        </Text>
                        ——
                        <Text
                          className={style["clickables"]}
                          onClick={gotoGift}
                        >
                          我的礼品卡
                        </Text>
                        中查看
                      </View>
                    </View>
                  ) : orderDetail.routes ? (
                    <View
                      className={`${style["top-border-section"]} ${style["bottom-border-section"]} ${style["misc-info"]}`}
                    >
                      <View className={style["misc-title"]}>
                        <Header type="heading-s">物流信息</Header>
                      </View>
                      <View>
                        {orderDetail.deliveryName && (
                          <View className={style["misc-content"]}>
                            <View className={style["delivery-title"]}>
                              <Icon type={"SF"} className={style.sf} />
                              顺丰速运：{orderDetail.masterWaybillNo}
                            </View>
                            <View className={style["delivery-info"]}>
                              {`【${orderDetail.routes.remark}】${orderDetail.routes.acceptTime || ""
                                }
                              ${orderDetail.routes.acceptAddress || ""}`}
                            </View>
                          </View>
                        )}
                      </View>
                    </View>
                  ) : (
                    <></>
                  )}

                  {!orderDetail.isGiftCard && (
                    <View className={style["address"]}>
                      <View className={style["go-to-addresses"]}>
                        <Header type="heading-s">收货信息</Header>
                      </View>
                      <View className={style["bottom-border-section"]}>
                        {/* Depending if there is a primary address or not */}
                        {orderDetail.userAddress && (
                          <KeyValueList
                            itemList={[
                              {
                                leftText: "姓名",
                                middleTextTop: orderDetail.realName,
                              },
                              {
                                leftText: "电话",
                                middleTextTop: orderDetail.userPhone,
                              },
                              {
                                leftText: "地址",
                                middleTextTop: orderDetail.userAddress,
                              },
                            ]}
                          />
                        )}
                      </View>
                    </View>
                  )}

                  <View className={style["bottom-border-section"]}>
                    {orderDetail.preOrderProductDetails.map(
                      (product, index) => {
                        return (
                          <View
                            key={product.productId + index}
                            className={style["shop-item-card"]}
                          >
                            <AbstractImage
                              type={"none"}
                              src={product.image}
                              className={style.image}
                            />
                            <View className={style.content}>
                              <View className={style["top-container"]}>
                                {product.cardNo && (
                                  <View className={style["card-tag"]}>
                                    礼品卡
                                  </View>
                                )}
                                <View
                                  className={style["name-itemcount-container"]}
                                >
                                  <View className={style.name}>
                                    {product.name}
                                  </View>
                                  <View className={style["prod-count"]}>
                                    x {product.buyNum}
                                  </View>
                                </View>
                                {product.sku !== "default" && (
                                  <View className={style["sku"]}>
                                    {product.sku}
                                  </View>
                                )}
                              </View>
                              <PriceView price={product.price} type={"small"} />
                              <View className={style.status}>
                                {[
                                  ApiRefundStatus.InApplication,
                                  ApiRefundStatus.BeingRefunded,
                                  ApiRefundStatus.ToBeReturned,
                                  ApiRefundStatus.BeingReturned,
                                ].includes(product.refundStatus)
                                  ? "退款中"
                                  : product.refundStatus ===
                                    ApiRefundStatus.Refunded
                                    ? "已退款"
                                    : product.refundStatus ===
                                      ApiRefundStatus.RefundCancelled
                                      ? "退款取消"
                                      : ""}
                              </View>
                            </View>
                          </View>
                        );
                      }
                    )}
                  </View>
                </View>
              )}

            {!!orderDetail.totalPrice && (
              <View
                className={`${style["price-section"]} ${style["bottom-border-section"]}`}
              >
                {/* TODO: Talk Luke: not recieved in data? */}
                {/* {!!orderDetail.couponPrice && (
                  <KeyValueList
                    itemList={[
                      {
                        leftText: UI_TEXT[orderDetail.type].priceText.main!,
                        rightNode: (
                          <PriceView
                            className={style.price}
                            price={+orderDetail.totalPrice}
                            type={"heading-n"}
                          />
                        ),
                      },
                      {
                        leftText:
                          UI_TEXT[orderDetail.type].priceText.supplementary!,
                        rightNode: (
                          // Exhibition: this field will be if there is a souvenir
                          // Talk/Course: could be negative value from applied gift card
                          <PriceView
                            className={style.price}
                            price={-orderDetail.couponPrice}
                            type={"heading-n"}
                          />
                        ),
                      },
                    ]}
                  />
                )} */}
                <View className={style["price-summary"]}>
                  <View className={style["total-intro"]}>
                    {UI_TEXT[orderDetail.type].priceText.totalIntro}
                  </View>
                  <View className={style["total-cost-calc"]}>
                    <View>
                      {UI_TEXT[orderDetail.type].priceText.summaryFormatter(
                        // NOTE: it's always showing 1 item and 1 people
                        // Because adding people will have separate order
                        // And for Shop Items, user can't change quantity
                        1,
                        1
                      )}
                    </View>
                    <View>合计</View>
                    <PriceView
                      className={style.price}
                      price={orderDetail.payPrice}
                      type="heading-n"
                    />
                  </View>
                </View>
              </View>
            )}

            <KeyValueList
              title="订单信息"
              itemList={[
                {
                  leftText: "订单编号",
                  middleTextTop: orderNo.replace("order", ""),
                },
                {
                  leftText: "创建时间",
                  middleTextTop: orderDetail.createTime,
                },
                {
                  leftText: "付款时间",
                  middleTextTop: !orderDetail.paid ? "" : orderDetail.payTime,
                },
              ]}
            />

            {parseFloat(orderDetail.totalPrice) >= 0.1 && (
              <View className={style.invoice}>
                <Header type="heading-n">发票服务</Header>
                <View
                  className={style["link"]}
                  onClick={() => {
                    const baseUrlGoTo = "pages/user-invoice-select/index";
                    const currentPages = getCurrentPages();
                    const prevPage = currentPages[currentPages.length - 2];
                    // If coming from page -> then navigate back instead
                    if (prevPage && prevPage.route === baseUrlGoTo) {
                      Taro.navigateBack();
                    } else {
                      // Else navigate to page and provide ID for prepopulation of selection
                      navigateTo(`${baseUrlGoTo}?id=${orderNo}`);
                    }
                  }}
                >
                  开发票
                </View>
              </View>
            )}
          </UserSubPageBase>
          <C13BottomDock
            onPrimaryClick={primaryCta}
            onSecondaryClick={secondaryCta}
          />
        </>
      )}
    </Layout>
  );
}
